class Base::NoticesController < ApplicationController
  before_action :set_base_notice, only: [:show, :update, :destroy]
  before_action :get_msg_count

  def index
    @html_title= '消息中心'
    @notices = Base::Notice.page(params[:page])
    params[:msg_type] ||= 'unread'
    if params[:msg_type].in? %w[readed unread deleted]
      @notices = @notices.received.send(params[:msg_type].to_sym).includes(:sender)
    elsif params[:msg_type] == 'sent'
      @notices = @notices.sent.includes(:receiver)
    end
  end

  def show
    @html_title = '消息详情'
    @notice.read! if @notice.status_unread? && @notice.to == current_user.id
    render layout: 'modal'
  end

  def update

  end

  def destroy

  end

  protected

  def set_base_notice
    @notice = Base::Notice.find(params[:id])
  end

  def get_msg_count
    msg_counts = Base::Notice.received.group(:status).pluck('status,count(id) t_count').to_h
    msg_counts.merge!('sent' => Base::Notice.sent.count)
    @msg_keys = %w[unread sent readed deleted]
    @msg_menu_infos = {
        'unread' =>   {'text' => '未读消息', 'icon' => 'fa-inbox', 'count' => msg_counts['unread'].to_i},
        'sent' =>     {'text' => '发件箱',   'icon' => 'fa-send', 'count' => msg_counts['sent'].to_i},
        'readed' => {'text' => '收件箱',   'icon' => 'fa-folder', 'count' => msg_counts['readed'].to_i},
        'deleted' =>  {'text' => '已删除',   'icon' => 'fa-trash', 'count' => msg_counts['deleted'].to_i}
    }
  end
end
